﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using System.Web.Script.Serialization;
using PServiceBus.Core.Provider;
using System.Text.RegularExpressions;
using Phoenix.ReflectionExtensions;
using PServiceBus.Core.Runtime.Serializers;
using PServiceBus.Core.Runtime.Extensions;
using System.Collections;
using PServiceBus.Core.Runtime.Transports;

namespace PServiceBus.Core.Runtime.Transformations {
    public class JsonTransformation : ITransformation {
        #region IDataTransformation Members
        static readonly ITransformation _xmlTransformation = new XmlTransformation();

        public string Transform(Dictionary<string, object> param) {
            return JsonSerializer.XmlToJson(_xmlTransformation.Transform(param), includeDictTypeInfo: false);
        }

        public string Transform(List<Dictionary<string, object>> list) {
            var result = new List<string>();
            foreach (var param in list) result.Add(Transform(param));
            return String.Concat("[", String.Join(",", result), "]");
        }

        public IEnumerable<TData> Transform<TData>(string data) where TData : class {
            var type = ReflectionHelper.GenerateInterface<TData>();
            return (SimpleJson.DeserializeObject(data, typeof(List<>).MakeGenericType(type)) as IList).Cast<TData>();
        }

        public Type GetCanonicalType(string data) {
            return this.ToCanonicalType((data.FromJson() as IList)[0] as Dictionary<string, object>);
        }
        #endregion
    }
}
